package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    private final CategoryBrandService categoryBrandService;

    public CategoryServiceImpl(CategoryBrandService categoryBrandService) {
        this.categoryBrandService = categoryBrandService;
    }

    @Override
    public List<CategoryDTO> queryCategoryByBrand(Long brandId) {
        // 根据品牌查询中间表 SELECT category_id FROM tb_category_brand WHERE brand_id = 43644
        List<CategoryBrand> cbList = categoryBrandService.query().eq("brand_id", brandId).list();

        // 从中间表对象中，获取分类的id
        List<Long> categoryIds = cbList.stream().map(CategoryBrand::getCategoryId).collect(Collectors.toList());

        // 根据分类id，查询分类集合 SELECT * FROM tb_category WHERE id IN (87, 88)
        List<Category> list = listByIds(categoryIds);

        // 转换DTO
        return CategoryDTO.convertEntityList(list);
    }
}
